package com.cpx.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Auther: PanBin
 * @Date: 2018-9-11 10:40
 * @Description: mvc的配置文件
 * @Version: 1.0
 */
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {

    /**
     * @Author: PanBin
     * @Description: 自定义的时间解析组件
     * @CreateDate: 2018-9-11 10:43
     * @Param [registry]
     * @Return void
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DateConverterConfig());
    }

    /**
     * @Author: PanBin
     * @Description: API返回值去除为NULL和""值，不序列化
     * @CreateDate: 2018-9-11 10:44
     * @Param [builder]
     * @Return com.fasterxml.jackson.databind.ObjectMapper
     */
    @Bean
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);//Include.Include.ALWAYS 默认 Include.NON_DEFAULT	属性为默认值不序列化 Include.NON_EMPTY	属性为 空（""） 或者为 NULL 都不序列化 Include.NON_NULL	属性为NULL 不序列化
        return objectMapper;
    }

    /**
     * @Author: PanBin
     * @Description: 启动使用定制的请求后缀
     * @CreateDate: 2018-8-29 9:52
     * @Return
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
        configurer.setUseTrailingSlashMatch(true);
        configurer.setUseRegisteredSuffixPatternMatch(true);
    }

    /**
     * @Author: PanBin
     * @Description: 设置controller的请求后缀
     * @CreateDate: 2018-9-11 10:48
     * @Param [dispatcherServlet]
     * @Return org.springframework.boot.web.servlet.ServletRegistrationBean
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean(DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean<DispatcherServlet> servletServletRegistrationBean = new ServletRegistrationBean<>(dispatcherServlet);
        servletServletRegistrationBean.addUrlMappings("/","*.html","*.do","*.css","*.js","*.jpg","*.png");
        return servletServletRegistrationBean;
    }
}
